import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, LoadingController } from 'ionic-angular';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import { RegisterPage } from './register/register'
import { HomePage } from '../home/home'
import { TabsPage } from '../tabs/tabs'
import { UserProvider } from '../../providers/service/user'
import { DEFINE } from '../../providers/Constants'
/**
 * Generated class for the LoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {

  accountForm: FormGroup;
  appName = DEFINE.appName;
  appIcon = DEFINE.appIcon;

  constructor(public navCtrl: NavController,
     public formBuilder: FormBuilder,
     public loadingCtrl: LoadingController,
     public userProvider: UserProvider,
     public navParams: NavParams) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad LoginPage');
    this.accountForm = this.formBuilder.group({
      "userName": ["", [Validators.required]],
      "password": ["", [Validators.required, Validators.minLength(6)]]
    });
  }

  register(){
    this.navCtrl.push(RegisterPage);
  }

  login(val){
    let loading = this.loadingCtrl.create({
      content: '正在登录，请稍等'
    });
    loading.present();
    this.userProvider.loginByUsername(val).then(res=>{
      // console.log(res);
      this.userProvider.getUserInfoByToken().then(res=>{
         // console.log(res);
        loading.dismiss();

        //更新jpushCode
        this.userProvider.updateJpushCode();

        //跳转页面
        this.navCtrl.setRoot(TabsPage);
        // this.navCtrl.setRoot(HomePage);

      },err=>{
        loading.dismiss();
      });
      
      //loading.dismiss();
    }, err => {
      loading.dismiss();
      console.log(err);
    });
  
  }

}
